package com.sans.security;

import com.sans.core.entity.Rule;
import com.sans.core.service.AdminService;
import com.sans.security.entity.SelfUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义权限注解验证
 * @author 123
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private AdminService adminService;
    /**
     * hasPermission鉴权方法
     * @param  authentication  用户身份(在使用hasPermission表达式时Authentication参数默认会自动带上)
     * @param  targetUrl  请求路径
     * @param  permission 请求路径权限
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        // 获取用户信息
        SelfUserEntity selfUserEntity =(SelfUserEntity) authentication.getPrincipal();
        // 查询用户权限(这里可以将权限放入缓存)
        Set<String> permissions = new HashSet<>();
        List<Rule> ruleList = adminService.selectSysMenuByUserId(selfUserEntity.getBid());
        for (Rule rule : ruleList) {
            permissions.add(rule.getRulePathinfo());
        }
        // 权限对比
        if (permissions.contains(permission.toString())){
            return true;
        }
        return false;
    }
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}